// const getCoursesApi = api.getCourses;

var OutlineVue = new Vue({
    el: "#outline_form",
    data: {
        grade: [{id: 1, name: '小学'},
            {id: 2, name: '初中'},
            {id: 3, name: '高中'},
            {id: 4, name: '大学'},],
        courses: [],
        selectRow:{name:'admin', intro:'init'},
        outlines:[]
    },
    created:function(){
        $.ajax({
            url:'/api/grade',
            type:'get',
            success: (res) => {
                this.grade = res.data;
            }
        })
    },
    methods: {
        async searchCourse (key, form) {
            // 获取年级
            var gradeId = $('#grade select').val();
            if(gradeId==''){
                layer.msg("情选择年级",{"icon":2})
                return;
            }
            $.ajax({
                url: "/api/course",
                type: "get",
                data: {key: key, gradeId:gradeId},
                success: (res) => {
                    console.log(res)
                    this.courses = res.data;
                    if (res.data != null && this.courses.length != 0) {
                        var select = $('#course select')
                        select.find('option.expected').siblings().remove()
                        for (var i = 0; i < this.courses.length; i++) {
                            var option = $(`<option value="${this.courses[i].id}">${this.courses[i].name}</option>`);
                            select.append(option)
                        }
                        form.render('select');
                        $('#course>div').addClass('layui-form-selected');
                        $('#course input').val(key).focus()
                    }
                }
            })
        },
    }
})



layui.config({
    base: '/layui/lay/modules/'
}).extend({
    treetable: 'treetable-lay/treetable'
}).use(['treetable', 'form', 'upload'], function () {
    // var $ = layui.jquery;
    var treetable = layui.treetable;
    var form = layui.form;
    var table = layui.table;

    var renderTable = function () {
        // layer.load(2);
        treetable.render({
            treeColIndex: 0,          // treetable新增参数
            treeSpid: -1,             // treetable新增参数
            treeIdName: 'd_id',       // treetable新增参数
            treePidName: 'd_pid',     // treetable新增参数
            treeDefaultClose: true,   // treetable新增参数
            treeLinkage: true,        // treetable新增参数
            elem: '#table1',
            url: '/api/outline/preview',
            cols: [[
                // {type: 'number'},
                // {field: 'id', title: 'id'},
                {field: 'num', title: '标号', width: 150},
                {field: 'name', title: '名称'},
                {field: 'intro', title: '介绍'},
                {templet: '#oper-col', title: '操作', width: 100}
                // {field: 'pid', title: 'pid'},
            ]]
        });
    };
    table.on('tool(table1)', function (obj) {
        var data = obj.data;
        var layEvent = obj.event;
        if (layEvent === 'edit') {
            var id = obj.id;
            OutlineVue.selectRow = data;
            editDialog("修改", 500, 400)
            form.val('editOutlineForm',{
                'id': data.id,
                'name':data.name,
                'intro':data.intro
            })
            form.render()
        }
    });
    form.on('submit(editOutlineSubmit)',(data)=>{
        data = data.field;
        console.log(data)
        $.ajax({
            url:'/api/outline/updateSessionOutline',
            type:'post',
            data:data,
            success:(res)=>{
                if(res.code ==0){
                    layuiUtil.msg.msgOk('修改成功');
                    renderTable()
                }
                window.setTimeout(()=>{
                    layer.closeAll()
                },500);
            }
        })
        return false;
    })
    // 渲染表格
    // var reloadTable = function (item) {
    //     treetable.reload("table1");
    // };
    // 如果session中有数据，需要渲染
    $.ajax({
        url: '/api/outline/preview',
        type:'get',
        success:(res)=>{
            if(res.success==true){
                renderTable()
            }
        }
    })


    // 文件上传
    var upload = layui.upload;
    //执行实例
    var uploadInst = upload.render({
        elem: '#outlineFile' //绑定元素
        , url: '/api/outline/file' //上传接口
        , exts: 'xlsx|xls'
        , before: function (obj) { //obj参数包含的信息，跟 choose回调完全一致，可参见上文。
            // layer.load(); //上传loading
        }
        , done: function (res) {
            //上传完毕回调
            console.log("上传完毕", res)
            renderTable()
        }
        , error: function () {
            //请求异常回调
        }
    });

    // 课程搜索
    // form.on('select(course)', function (data) {
    //     console.log(data)
    // })

    var timer = null;
    $(document).on('input propertychange', '#course input', function (e) {
        if (timer == null) {
            timer = window.setTimeout(() => {
                OutlineVue.searchCourse($(this).val(), form);
            }, 500);
        } else {
            window.clearTimeout(timer);
            timer = window.setTimeout(() => {
                OutlineVue.searchCourse($(this).val(), form);
            }, 500);
        }

    });

    form.verify({
        name: function (value, item) { //value：表单的值、item：表单的DOM对象
            if (value.trim() == "") {
                return '大纲名称不能为空';
            }
            var param = {
                courseId: $("#course select").val(),
                name: value
            }
            var checkResult = "";

            $.ajax({
                url: "/api/outline/checkName",
                type: "post",
                data: param,
                async: false,
                success: function (result) {
                    if (result.data.exists == true) {
                        checkResult = "该大纲已存在";
                    }
                },
                error: function () {
                }
            });
            return checkResult;
        }
    });


    //表单提交
    form.on('submit(formDemo)', function (data) {
        // 查询session中是否还有数据
        var data = data.field;
        $.ajax({
            url:'/api/outline',
            type:'post',
            data:data,
            success: (res) =>{
                if(res.success == true){
                    layer.msg("上传成功",{icon:1})
                    window.location.href = '/teacher/outline/manage.html';
                }
            }
        })

        return false;
    })

});

function editDialog(title, w, h) {
    if (title == null || title == '') {
        title = false;
    }
    if (w == null || w == '') {
        w = ($(window).width() * 0.9);
    }
    if (h == null || h == '') {
        h = ($(window).height() - 50);
    }
    ;
    layui.use('layer', (layer)=>{
        index = layer.open({  //layer提供了5种层类型。可传入的值有：0（信息框，默认）1（页面层）2（iframe层）3（加载层）4（tips层）
            type: 1,
            title: title,
            // area: ['25%', '55%'],//类型：String/Array，默认：'auto'  只有在宽高都定义的时候才不会自适应
            area: [w + 'px', h + 'px'],
            fix: false, //不固定
            maxmin: true,//开启最大化最小化按钮
            shadeClose: true,//点击阴影处可关闭
            shade: 0.4,//背景灰度
            skin: 'layui-layer-rim', //加上边框
            content: $("#outline_edit_box").html()
        });
    })

}

